<template>
  <div class="court-container">
    <el-card class="court-card">
      <template #header>
        <div class="card-header">
          <h3>法院信息管理</h3>
          <el-button type="success" @click="handleAdd">+ 新增法院</el-button>
        </div>
      </template>

      <el-form :model="queryForm" :inline="true" @submit.prevent="handleQuery">
        <el-form-item label="关键词搜索">
          <el-input v-model="queryForm.keywords" placeholder="请输入法院名称或ID" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="courtList" border stripe v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="法院名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="level" label="法院级别" width="120">
          <template #default="{ row }">
            <el-tag>{{ getLevelText(row.level) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="full_address" label="地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="create_time" label="创建时间" width="160" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)">查看</el-button>
            <el-dropdown>
              <el-button size="small" type="primary" link>
                更多
                <el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleEdit(row)">编辑</el-dropdown-item>
                  <el-dropdown-item @click="handleDelete(row)">删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="queryForm.page"
        v-model:page-size="queryForm.limit"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 法院详情抽屉 -->
    <GlobalDrawer
      v-model="drawerVisible"
      :title="drawerTitle"
      size="60%"
      :before-close="handleBeforeClose"
      @confirm="handleSubmit"
      @cancel="handleDrawerClose"
      :show-footer-buttons="!isViewMode"
    >
      <template #default>
        <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
          <el-form-item label="法院名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入法院名称" :disabled="isViewMode" />
          </el-form-item>
          <el-form-item label="法院级别" prop="level">
            <el-select
              v-model="form.level"
              placeholder="请选择法院级别"
              style="width: 100%"
              :disabled="isViewMode"
            >
              <el-option label="中华人民共和国最高人民法院" value="1" />
              <el-option label="高级人民法院" value="2" />
              <el-option label="中级人民法院" value="3" />
              <el-option label="基层人民法院" value="4" />
              <el-option label="专门人民法院" value="5" />
              <el-option label="人民法庭" value="6" />
              <el-option label="其他司法机构" value="7" />
            </el-select>
          </el-form-item>
          <el-form-item label="所在地区" prop="province">
            <RegionCascader
              v-model="regionData"
              :disabled="isViewMode"
              placeholder="请选择省/市/区"
              @change="handleRegionChange"
            />
          </el-form-item>
          <el-form-item label="详细地址" prop="address">
            <el-input
              v-model="form.address"
              type="textarea"
              placeholder="请输入详细地址"
              :disabled="isViewMode"
            />
          </el-form-item>
        </el-form>
      </template>
    </GlobalDrawer>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, watch, computed } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { ArrowDown } from '@element-plus/icons-vue'
  import { GlobalDrawer } from '@/components/common'
  import { RegionCascader } from '@/components/business/region'
  import { courtApi, type CourtItem } from '@/api/lawcaseCourt'

  // 数据列表
  const courtList = ref<CourtItem[]>([])
  const loading = ref(false)
  const total = ref(0)

  // 查询表单
  const queryForm = reactive({
    page: 1,
    limit: 10,
    keywords: '',
  })

  // 抽屉
  const drawerVisible = ref(false)
  const drawerTitle = ref('')
  const isViewMode = ref(false)

  // 地区数据
  const regionData = ref<string>('')

  // 表单数据
  const form = reactive({
    id: undefined as number | undefined,
    name: '',
    level: '4',
    province: '',
    city: '',
    district: '',
    address: '',
    status: 1,
  })

  // 表单验证规则
  const rules = {
    name: [{ required: true, message: '请输入法院名称', trigger: 'blur' }],
    level: [{ required: true, message: '请选择法院级别', trigger: 'change' }],
    province: [{ required: true, message: '请选择所在地区', trigger: 'change' }],
  }

  // 表单引用
  const formRef = ref()

  // 法院级别映射
  const courtLevelMap: { [key: string]: string } = {
    '1': '最高法院',
    '2': '高级法院',
    '3': '中级法院',
    '4': '基层法院',
    '5': '专门法院',
    '6': '人民法庭',
    '7': '其他司法机构',
  }

  // 获取法院级别文本
  const getLevelText = (level: string | number): string => {
    const levelStr = String(level)
    return courtLevelMap[levelStr] || levelStr
  }

  /**
   * 获取法院列表数据
   */
  const getCourtList = async () => {
    loading.value = true
    try {
      const res = await courtApi.getCourtList(queryForm)
      if (res.code === 0) {
        // 根据后端实际返回的数据结构进行处理
        if (Array.isArray(res.data)) {
          courtList.value = res.data
        } else if (res.data && Array.isArray((res.data as any).list)) {
          courtList.value = (res.data as any).list
        } else {
          courtList.value = []
        }
        total.value = res.count || 0
      } else {
        ElMessage.error(res.msg || '获取法院列表失败')
      }
    } catch (error) {
      ElMessage.error('获取法院列表失败')
    } finally {
      loading.value = false
    }
  }

  // 查询
  const handleQuery = () => {
    queryForm.page = 1
    getCourtList()
  }

  // 重置
  const handleReset = () => {
    queryForm.keywords = ''
    queryForm.page = 1
    getCourtList()
  }

  // 分页
  const handleSizeChange = (val: number) => {
    queryForm.limit = val
    getCourtList()
  }

  const handleCurrentChange = (val: number) => {
    queryForm.page = val
    getCourtList()
  }

  // 处理地区选择变化
  const handleRegionChange = (value: string | string[] | null, selectedOptions: any[]) => {
    if (value && selectedOptions && selectedOptions.length > 0) {
      // 从selectedOptions中获取完整的省市区信息
      const province = selectedOptions[0]
      const city = selectedOptions.length > 1 ? selectedOptions[1] : null
      const district = selectedOptions.length > 2 ? selectedOptions[2] : null

      // 使用id字段而不是code字段，并确保转换为字符串
      form.province = province?.id ? String(province.id) : ''
      form.city = city?.id ? String(city.id) : ''
      form.district = district?.id ? String(district.id) : ''
    } else if (value) {
      // 如果没有selectedOptions，尝试从value中解析
      if (Array.isArray(value)) {
        // 如果value是数组，取最后一个值作为区县代码
        form.district = value.length > 0 ? String(value[value.length - 1]) : ''
        // 如果数组长度大于1，设置市
        if (value.length > 1) {
          form.city = String(value[value.length - 2]) || ''
        }
        // 如果数组长度大于2，设置省
        if (value.length > 2) {
          form.province = String(value[0]) || ''
        }
      } else if (typeof value === 'string' && value.includes('/')) {
        // 如果value是完整路径字符串，解析它
        const codes = value.split('/')
        form.province = codes[0] || ''
        form.city = codes[1] || ''
        form.district = codes[2] || ''
      } else {
        // 否则使用value作为区县代码
        form.district = String(value) || ''
      }
    } else {
      form.province = ''
      form.city = ''
      form.district = ''
    }
  }

  // 监听地区数据变化
  watch(
    () => [form.province, form.city, form.district],
    ([province, city, district]) => {
      // 如果有完整的省市区数据，则更新regionData
      if (province && city && district) {
        // RegionCascader组件需要完整的路径字符串，格式为 "省份代码/城市代码/区县代码"
        regionData.value = `${province}/${city}/${district}`
      } else if (province && city) {
        regionData.value = `${province}/${city}`
      } else if (province) {
        regionData.value = province
      } else {
        regionData.value = ''
      }
    },
    { immediate: true }
  )

  // 新增
  const handleAdd = () => {
    drawerTitle.value = '新增法院'
    isViewMode.value = false
    Object.assign(form, {
      id: undefined,
      name: '',
      level: '4',
      province: '',
      city: '',
      district: '',
      address: '',
      status: 1,
    })
    regionData.value = ''
    drawerVisible.value = true
  }

  // 查看
  const handleView = (row: CourtItem) => {
    drawerTitle.value = '查看法院'
    isViewMode.value = true
    Object.assign(form, {
      id: row.id,
      name: row.name,
      level: row.level?.toString() || '4',
      province: row.provinceid?.toString() || '',
      city: row.cityid?.toString() || '',
      district: row.distid?.toString() || '',
      address: row.address,
      status: row.status,
    })
    drawerVisible.value = true
  }

  // 编辑
  const handleEdit = (row: CourtItem) => {
    drawerTitle.value = '编辑法院'
    isViewMode.value = false
    Object.assign(form, {
      id: row.id,
      name: row.name,
      level: row.level?.toString() || '4',
      province: row.provinceid?.toString() || '',
      city: row.cityid?.toString() || '',
      district: row.distid?.toString() || '',
      address: row.address,
      status: row.status,
    })
    drawerVisible.value = true
  }

  // 删除
  const handleDelete = (row: CourtItem) => {
    ElMessageBox.confirm('确定要删除该法院信息吗？', '提示', {
      type: 'warning',
    })
      .then(async () => {
        try {
          const res = await courtApi.deleteCourt(row.id)
          if (res.code === 0) {
            ElMessage.success('删除成功')
            getCourtList()
          } else {
            ElMessage.error(res.msg || '删除失败')
          }
        } catch (error) {
          ElMessage.error('删除失败')
        }
      })
      .catch(() => {})
  }

  // 提交表单
  const handleSubmit = () => {
    if (isViewMode.value) {
      drawerVisible.value = false
      return
    }

    formRef.value.validate(async (valid: boolean) => {
      if (valid) {
        try {
          const formData: any = {
            court_name: form.name,
            level: form.level,
            province: form.province,
            city: form.city,
            district: form.district,
            address: form.address,
            status: form.status,
          }

          let res
          if (form.id) {
            // 编辑
            formData.id = form.id
            res = await courtApi.editCourt(formData)
          } else {
            // 新增
            res = await courtApi.addCourt(formData)
          }

          if (res.code === 0) {
            ElMessage.success(form.id ? '编辑成功' : '新增成功')
            drawerVisible.value = false
            getCourtList()
          } else {
            ElMessage.error(res.msg || (form.id ? '编辑失败' : '新增失败'))
          }
        } catch (error) {
          ElMessage.error(form.id ? '编辑失败' : '新增失败')
        }
      }
    })
  }

  // 处理抽屉关闭
  const handleDrawerClose = () => {
    drawerVisible.value = false
  }

  // 处理抽屉关闭前的确认
  const handleBeforeClose = (): boolean => {
    return true
  }

  // 初始化
  onMounted(() => {
    getCourtList()
  })
</script>

<style scoped>
  .court-container {
    padding: 20px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .card-header h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 500;
  }

  .court-card {
    margin-bottom: 20px;
  }

  /* 新增按钮样式 */
  .card-header :deep(.el-button--success) {
    background: linear-gradient(to right, #67c23a, #85ce61, #9adb75);
    border-color: #67c23a;
  }
</style>
